package itsec1.customermanagement;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

public class RSAEncryption {
	private Cipher decryption = null;
	private Cipher encryption = null;

	private static final String RSA_ALGORITHM = "RSA/NONE/OAEPWithSHA256AndMGF1Padding";
	private static final String RSA_PROVIDER = "BC";

	public RSAEncryption(KeyPair keyPair) throws GeneralSecurityException {
		decryption = Cipher.getInstance(RSA_ALGORITHM, RSA_PROVIDER);
		decryption.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

		encryption = Cipher.getInstance(RSA_ALGORITHM, RSA_PROVIDER);
		encryption.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
	}

	public RSAEncryption(PrivateKey decryptionKey)
			throws GeneralSecurityException {
		decryption = Cipher.getInstance(RSA_ALGORITHM, RSA_PROVIDER);
		decryption.init(Cipher.DECRYPT_MODE, decryptionKey);
	}

	public RSAEncryption(PublicKey encryptionKey)
			throws GeneralSecurityException {
		encryption = Cipher.getInstance(RSA_ALGORITHM, RSA_PROVIDER);
		encryption.init(Cipher.ENCRYPT_MODE, encryptionKey);
	}

	// encrypt data with public key
	public byte[] encrypt(byte[] text) throws IOException {
		try {
			byte[] encryptedData = this.encryption.doFinal(text);

			return encryptedData;
		} catch (GeneralSecurityException e) {
			throw new IOException("Could not encrypt data", e);
		}
	}

	public byte[] encrypt(String text) throws IOException {
		return encrypt(text.getBytes());
	}

	// decrypt data with private key
	public String decrypt(byte[] encryptedData) throws IOException {
		return new String(decryptAsBytes(encryptedData));
	}

	public byte[] decryptAsBytes(byte[] encryptedData) throws IOException {
		try {
			return this.decryption.doFinal(encryptedData);
		} catch (GeneralSecurityException e) {
			throw new IOException("Could not decrypt data", e);
		}
	}
}
